import { _decorator, CapsuleCollider, Collider, Component, game, instantiate, ITriggerEvent, Layers, Node, ParticleSystem, Prefab } from 'cc';
import { GameManager } from '../Managers/GameManager';
import { TankManager } from '../Managers/TankManager';
import { ExplosionManager } from '../Managers/ExplosionManager';
const { ccclass, property } = _decorator;

@ccclass('ShellExplosion')
export class ShellExplosion extends Component {

    @property({ type: Layers.BitMask })
    public tankMask: number = 0;                           // Used to filter what the explosion affects, this should be set to "Players".

    @property(Prefab)
    public explosionPrefab: Prefab = null;

    private explosionParticles: ParticleSystem = null;      // Reference to the particles that will play on explosion.

    @property
    public maxDamage: number = 100;                       // The amount of damage done if the explosion is centred on a tank.

    @property
    public explosionForce: number = 1000;                 // The amount of force added to a tank at the centre of the explosion.

    @property
    public maxLifeTime: number = 2;                       // The time in seconds before the shell is removed.

    @property
    public explosionRadius: number = 1;                   // The maximum distance away from the explosion tanks can be and are still affected.

    start() {
        // If it isn't destroyed by then, destroy the shell after it's lifetime.
        setTimeout(() => {
            if (this.node && this.node.isValid) {
                this.node.destroy();
            }
        }, this.maxLifeTime * 1000); // Convert seconds to milliseconds

        let collider = this.node.getComponent(CapsuleCollider);
        collider.on('onTriggerEnter', this.onTriggerEnter, this);
    }

    private onTriggerEnter(event: ITriggerEvent) {
        // Get all colliders within explosion radius
        //const colliders = this.node.getComponent(Collider)?.getOverlapSphere(this.node.position, this.explosionRadius) || [];
        //console.log('Trigger entered at position:', event.worldPosition);
        const explosionprefab = instantiate(this.explosionPrefab)
        explosionprefab.setParent(this.node.parent);
        explosionprefab.worldPosition = this.node.worldPosition;
        explosionprefab.getComponent(ParticleSystem).play();
        const gameTime = game.totalTime/ 1000;
        const tanks: TankManager[] =
            ExplosionManager.getInstance().judgeExplosionHurt(this.node.worldPosition, this.explosionRadius);
        if (tanks != null) {
            for (let i = 0; i < tanks.length; i++) {
                tanks[i].health.takeDamage(10);
            }
        }
        this.node.destroy();
        console.log(event.otherCollider.name);
        // Destroy shell
        //this.node.destroy();
    }

}

